package com.automation.ljf.strategy.impl;

import com.automation.ljf.domain.dataobject.CaseStepDO;
import com.automation.ljf.strategy.OperationStrategy;
import com.automation.ljf.util.DriverUtils;
import com.automation.ljf.util.ResultMessage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 判断元素的文本值与预期是否一样
 *
 * @author lijiefeng
 * @since 2021/8/30
 */
@Component("JUDGE_VALUE")
public class JudgeValueStrategyImpl implements OperationStrategy {

    @Override
    public ResultMessage doOperation(ChromeDriver driver, CaseStepDO caseStepDO, String jsonData) {
        //获取窗口句柄
        String windowHandle = driver.getWindowHandle();
        if (!DriverUtils.isElementExist(driver, By.xpath(caseStepDO.getStepXpath()))){
            return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                    .addData("errorMsg", "元素不存在，无法定位").addData("window", windowHandle);
        }
        WebElement we = driver.findElement(By.xpath(caseStepDO.getStepXpath()));
        if (!we.isDisplayed()){
            return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                    .addData("errorMsg", "元素不显示，无法获取")
                    .addData("window", windowHandle);
        }
        //获取元素的文本值
        String content = we.getText();
        if (!caseStepDO.getExpectResult().equals("TRUE") && !Objects.equals(content, caseStepDO.getExpectResult())){
            return ResultMessage.error("测试用例" + caseStepDO.getCaseId() + "的步骤" + caseStepDO.getStepId() + "出现异常")
                    .addData("errorMsg", "元素显示的文本值与期望结果不符")
                    .addData("window", windowHandle)
                    .addData("content", content);
        }
        return ResultMessage.ok("操作成功").addData("content", content).addData("window", windowHandle);
    }

}
